<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<head>
    <link rel="stylesheet" href="${APP_PATH}/static/layui/css/layui.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/main.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/index.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/main_page.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/query.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/select2.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/plugins/public_components/css/form.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/plugins/public_components/css/query.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/plugins/public_components/css/select2.css" type="text/css"/>
    <link rel="stylesheet" href="${APP_PATH}/plugins/public_components/css/ace.min.css" type="text/css"/>
    <%--行编辑样式--%>
    <%--<link rel="stylesheet" href="layui/css/layui.css?v=201805080202" />--%>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<script src="${APP_PATH}/static/layui/layui.all.js"></script>
<script src="${APP_PATH}/plugins/public_components/js/iTsai-webtools.form.js"></script>
<script src="${APP_PATH}/plugins/public_components/js/jquery-1.10.2.min.js"></script>
<script src="${APP_PATH}/plugins/public_components/js/select2.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="yclOutsourcingOrderPage" style="margin: 30px">
    <%--query tools--%>
        <form id="goods_list_hiddenQueryForm" style="display:none;">
            <input name="warehouse" value="">
            <input name="shiftcode" value="">
        </form>
        <div class="query_box" id="goods_list_yy" title="查询选项">
            <form id="goods_list_queryForm" style="max-width:100%;">
                <ul class="form-elements">
                    <li class="field-group field-fluid3">
                        <label class="inline" for="goods_list_warehouse" style="margin-right:20px;width: 100%;">
                            <span class="form_label" style="width:80px;">子库：</span>
                            <input id="goods_list_warehouse" name="warehouse" type="text" style="width:  calc(100% - 85px);" placeholder="仓库">
                        </label>
                    </li>
                    <li class="field-group field-fluid3">
                        <label class="inline" for="goods_list_code" style="margin-right:20px;width:100%;">
                            <span class='form_label' style="width:80px;">生产厂：</span>
                            <input type="text" name="code" id="goods_list_code" value="" style="width: calc(100% - 85px);" placeholder="生产厂">
                        </label>
                    </li>
                    <li class="field-group field-fluid3">
                        <label class="inline" for="goods_list_code" style="margin-right:20px;width:100%;">
                            <span class='form_label' style="width:80px;">物料编号：</span>
                            <input type="text" name="item_code" id="item_code" value="" style="width: calc(100% - 85px);" placeholder="物料编号">
                        </label>
                    </li>
                    <li class="field-group field-fluid3">
                        <label class="inline" for="goods_list_code" style="margin-right:20px;width:100%;">
                            <span class='form_label' style="width:80px;">机台：</span>
                            <input type="text" name="device_name" id="device_name" value="" style="width: calc(100% - 85px);" placeholder="机台">
                        </label>
                    </li>
                    <li class="field-group field-fluid3">
                        <label class="inline" for="goods_list_shift_code" style="margin-right:20px;width: 100%;">
                            <span class="form_label" style="width:80px;">班次：</span>
                            <input id="goods_list_shift_code" name="shiftcode" type="text" style="width:  calc(100% - 85px);" placeholder="班次">
                        </label>
                    </li>
                </ul>
                <div class="field-button" style="">
                    <div class="btn btn-info" onclick="goods_list_queryOk();">
                        <i class="ace-icon fa fa-check bigger-110"></i>查询
                    </div>
                    <div class="btn" onclick="goods_list_reset();"><i class="ace-icon icon-remove"></i>重置</div>
                    <!-- <a style="margin-left: 8px;color: #40a9ff;" class="toggle_tools">收起 <i class="fa fa-angle-up"></i></a> -->
                </div>
            </form>
        </div>

    <%-- table grid --%>
    <table id="tableGridOutsourcing" lay-filter="tableGridFilterOutsourcing"></table>
    <table id="tableGridOutsourcing3" lay-filter="tableGridFilterOutsourcing3"></table>
    <%-- table grid toolbar --%>
    <script type="text/html" id="tableGridToolbarOutsourcing">
        <div class="layui-btn-container">
            <label class="layui-word-aux">领料申请单</label>
        </div>
    </script>
    <script type="text/html" id="tableGridToolbarOutsourcing3">
        <div class="layui-btn-container">
            <label class="layui-word-aux">入库单列表</label>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="addIn">
                <i class="layui-icon">&#xe654;</i>增行
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="save">
                <i class="layui-icon">&#xe605;</i>出库
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">
                <i class="layui-icon">&#xe640;</i>清除
            </button>
        </div>
    </script>
</div>


<script>

    const context_path = '${APP_PATH}';
    const table = layui.table,
        layer = layui.layer,
        laydate = layui.laydate;

    let tableGridIns3;

    let tableGridIns;

    //准备视图对象
    window.viewObj = {
        tableGridSet3Data: {},
        wareHouseListTable: [],
        renderSelectOptions: function (data, settings) {
            settings = settings || {};
            let valueField = settings.valueField || 'value',
                textField = settings.textField || 'text',
                selectedValue = settings.selectedValue || "";
            let html = [];
            for (let i = 0, item; i < data.length; i++) {
                item = data[i];
                html.push('<option value="');
                html.push(item[valueField]);
                html.push('"');
                if (selectedValue && item[valueField] == selectedValue) {
                    html.push(' selected="selected"');
                }
                html.push('>');
                html.push(item[textField]);
                html.push('</option>');
            }
            return html.join('');
        }
    };

    //获取table的list集合
    let vm = new Vue({
        el: '#yclOutsourcingOrderPage',
        data: {
            queryParams: { //查询参数
                poCode: "",
                supplierName: "",
                materialCode: "",
                purchaseUser: "",
                orderTimeStart: "",
                orderTimeEnd: "",
                poNum: ""
            }
        },
        methods: {
            initTableIns() {
                // 订单物料
                tableGridIns = table.render({
                    elem: '#tableGridOutsourcing'
                    , url: context_path + '/ycl/production/picking/list'
                    , page: true
                    , toolbar: '#tableGridToolbarOutsourcing'
                    , id: "tableGridSetOutsourcing"
                    , size: 'sm'
                    , defaultToolbar: []
                    , cols: [[
                        {field: 'moCode', title: '领料单号', width: 200}
                        , {field: 'lineNum', title: '领料行号', width: 85}
                        , {field: 'itemCode', title: '物料编码', width: 125}
                        , {field: 'itemDesc', title: '物料名称', width: 255}
                        , {field: 'shiftCode', title: '班次', width: 100}
                        , {field: 'deviceName', title: '机台', width: 150}
                        , {field: 'quantity', title: '领料数量', width: 105}
                        , {field: 'fromSubinvDesc', title: '库位', width: 205}
                        , {field: 'facName', title: '领料生产厂', width: 155}
                        , {field: 'opName', title: '工序', width: 155}
                        , {field: 'userName', title: '申请人', width: 125}
                        , {field: 'needByDate', title: '申请日期', width: 225}
                    ]]
                });
            },

            //第三栏
            initTableIns3() {
                tableGridIns3 = table.render({
                    elem: '#tableGridOutsourcing3'
                    // , url: context_path + '/ycl/operation/yclInOutFlow/list'
                    , toolbar: '#tableGridToolbarOutsourcing3'
                    , id: "tableGridSetOutsourcing3"
                    , defaultToolbar: []
                    , limit: 99999
                    , data: []
                    , cols: [[
                        {type: 'checkbox'}
                        , {field: 'moCode', title: '领料单号', width: 200}
                        , {field: 'lineNum', title: '领料行号', width: 85}
                        , {field: 'itemCode', title: '物料编码', width: 125}
                        , {field: 'itemDesc', title: '物料名称', width: 255}
                        , {field: 'shiftCode', title: '班次', width: 100}
                        , {field: 'deviceName', title: '机台', width: 150}
                        , {field: 'quantity', title: '领料数量', width: 105}
                        , {field: 'outQuantity', title: '配送数量', width: 105, edit: 'text'}
                        , {field: 'package', title: '件数', width: 105, edit: 'text'}
                        , {field: 'lotsNum', title: '批次号', width: 105, edit: 'text'}
                        , {field: 'locatorCode', title: '库位编码', width: 105, edit: 'text'}
                        , {field: 'primaryUomCode', title: '单位', width: 205}
                        , {field: 'fromSubinvDesc', title: '来源子库', width: 205}
                        , {field: 'facName', title: '领料生产厂', width: 155}
                        , {field: 'opName', title: '工序', width: 155}
                        , {field: 'userName', title: '申请人', width: 125}
                        , {field: 'needByDate', title: '申请日期', width: 225}
                    ]]
                });
            },
            //仓库
            initWareHouseList() {
                $.get(context_path + '/warehouselist/yclList.do', {rows: '9999'}, function (res) {
                    console.log(res)
                    viewObj.wareHouseListTable = res.rows
                })
            },

            queryPageView() {
                console.log(vm.queryParams)
                table.reload('tableGridSetOutsourcing', {
                    where: vm.queryParams
                });
            },
            restQueryParams() {
                vm.queryParams = {
                    poCode: "",
                    supplierName: "",
                    materialCode: "",
                    purchaseUser: "",
                    orderDate: ""
                }
            }
        },
        created() {

        },
        mounted() {

        }

    })

    table.on('toolbar(tableGridFilterOutsourcing3)', function (obj) {
        const checkStatusData = table.checkStatus(obj.config.id).data
        let oldData = table.cache['tableGridSetOutsourcing3'];
        switch (obj.event) {
            case 'addIn':
                console.log(oldData);
                let newRow = oldData[0];
                oldData.push(newRow);
                console.log(oldData);
                console.log(tableGridIns3);
                tableGridIns3.reload({
                    // console.log(oldData);
                    data: oldData
                })
                break;
            case 'save' :

                if(checkStatusData.length == 0){
                    Dialog.alert("请选择要出库的数据");
                    return;
                }

                let total_quantity = checkStatusData[0].quantity;

                var add_quantity = 0;

                for(var i = 0; i < checkStatusData.length; i++){
                    if(!checkStatusData[i].outQuantity){
                        Dialog.alert("请填写第" + (i + 1) + "行的配送数量");
                        return;
                    }
                    if(!checkStatusData[i].package){
                        Dialog.alert("请填写第" + (i + 1) + "行的件数");
                        return;
                    }
                    if(!checkStatusData[i].lotsNum){
                        Dialog.alert("请填写第" + (i + 1) + "行的批次号");
                        return;
                    }
                    if(!checkStatusData[i].locatorCode){
                        Dialog.alert("请填写第" + (i + 1) + "行的库位编码");
                        return;
                    }
                    var outQuantity = checkStatusData[i].outQuantity == ''?0:checkStatusData[i].outQuantity;
                    add_quantity += outQuantity*1;
                }

                console.log(add_quantity);

                if(add_quantity > total_quantity){
                    Dialog.alert("配送数量的和不能大于领料数量");
                    return;
                }

                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/production/picking/save",
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(checkStatusData),
                    success: function (res) {
                        console.log(res)
                        if (res.result === false) {
                            layer.msg(res.msg, {icon: 5});
                            return false;
                        } else {
                            layer.msg(res.msg, {icon: 1});
                            let data= [];
                            tableGridIns3.reload({
                                // console.log(oldData);
                                data: data
                            });
                            tableGridIns.reload();
                            //刷新父页面
                            // parent.location.reload();
                        }
                    }
                })

                break;
            case 'delete' :
                if (checkStatusData.length === 0) {
                    layer.msg('至少选择一条数据', {icon: 2});
                    return
                }
                console.log(obj.tr)
                console.log(checkStatusData)

                oldData.splice(obj.config.data('index'),1);

                tableGridIns3.reload({
                    data: oldData
                })

                // let ids = checkStatusData.map(item => item.id).toString()
                // console.log(ids)
                // $.get(context_path + '/ycl/operation/yclInOutFlow/delete', {ids}, function (res) {
                //     layer.msg(res.msg);
                //     table.reload('tableGridSet3');
                // })
                break;
        }
    });

    // 监听编辑单元格
    table.on('edit(tableGridFilterOutsourcing3)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
        console.log(obj.value); //得到修改后的值
        console.log(obj.field); //当前编辑的字段名
        console.log(obj.data); //所在行的所有相关数据
    });

    // 点击订单物料
    table.on('row(tableGridFilterOutsourcing)', function (obj) {
        const data = obj.data;

        let oldData = table.cache['tableGridSetOutsourcing3'];
        console.log(oldData.length);
        if(oldData.length > 0){
            var oldlineid = oldData[0].lineId;

            if(data.lineId != oldlineid) {
                Dialog.confirm("是否清空列表重新录入?", function () {
                    let newdata = [];

                    newdata.push(data);

                    tableGridIns3.reload({
                        // console.log(oldData);
                        data: newdata
                    })
                },function(){
                    return false;
                })
            }
        } else {
            console.log(data);
            let newdata = [];

            newdata.push(data);

            tableGridIns3.reload({
                // console.log(oldData);
                data: newdata
            })
        }


        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });

    const goods_list_queryForm_data = iTsai.form.serialize($("#goods_list_queryForm"));

    function goods_list_queryOk(){
        //执行父窗口中的js方法：将当前窗口中的form的值传递到父窗口，并放到父窗口中隐藏的form中，接着执行刷新父窗口列表的操作
        goods_list_queryByParam(iTsai.form.serialize($("#goods_list_queryForm")));
    }

    //重置
    function goods_list_reset(){
        $("#goods_list_queryForm #goods_list_warehouse").select2("val","");
        iTsai.form.deserialize($("#goods_list_queryForm"),goods_list_queryForm_data);
    }

    // init
    ;!function () {

        $("#goods_list_queryForm #goods_list_warehouse").select2({
            placeholder: "选择仓库",
            minimumInputLength: 0, //至少输入n个字符，才去加载数据
            allowClear: true, //是否允许用户清除文本信息
            delay: 250,
            formatNoMatches: "没有结果",
            formatSearching: "搜索中...",
            formatAjaxError: "加载出错啦！",
            ajax: {
                url: context_path + "/car/selectWarehouse",
                type: "POST",
                dataType: 'json',
                delay: 250,
                data: function (term, pageNo) { //在查询时向服务器端传输的数据
                    term = $.trim(term);
                    return {
                        queryString: term, //联动查询的字符
                        pageSize: 15, //一次性加载的数据条数
                        pageNo: pageNo
                    }
                },
                results: function (data, pageNo) {
                    const res = data.result;
                    if (res.length > 0) { //如果没有查询到数据，将会返回空串
                        const more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                        return {
                            results: res,
                            more: more
                        };
                    } else {
                        return {
                            results: {}
                        };
                    }
                },
                cache: true
            }
        });

        $("#goods_list_queryForm #goods_list_shift_code").select2({
            placeholder: "选择班次",
            minimumInputLength: 0, //至少输入n个字符，才去加载数据
            allowClear: true, //是否允许用户清除文本信息
            delay: 250,
            formatNoMatches: "没有结果",
            formatSearching: "搜索中...",
            formatAjaxError: "加载出错啦！",
            ajax: {
                url: context_path + "/wms2/baseinfo/factorymachine/selectShiftCode",
                type: "POST",
                dataType: 'json',
                delay: 250,
                results: function (data, pageNo) {
                    const res = data.result;

                    if (res.length > 0) { //如果没有查询到数据，将会返回空串
                        return {
                            results: res,
                            more: true
                        };
                    } else {
                        return {
                            results: {}
                        };
                    }
                },
                cache: true
            }
        });

        vm.initTableIns()
        vm.initTableIns3()

    }();
</script>